package hc.j2me;

import hc.core.ConditionWatcher;
import hc.core.HCTimer;
import hc.core.IWatcher;
import hc.core.sip.ISIPContext;
import hc.core.sip.SIPManager;
import hc.j2me.ui.UIManager;

import java.io.IOException;

import javax.microedition.io.UDPDatagramConnection;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class Main extends MIDlet {
	public static Main main;
	public Main() {		
	}

	public void destroyApp(boolean arg0) throws MIDletStateChangeException {
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		if(main == null){
			main = this;
			
			UIManager.setMainMIDlet(this);
	
			final GameCanvas f = new FirstGameCanvas(false);

			UIManager.pushInAndSwithToNew(f);
			ConditionWatcher.addWatcher(new IWatcher() {
				public boolean watch() {
					new Starter();
					return true;
				}
				public void setPara(Object p) {
				}
				public void cancel() {
				}
				public boolean isNotCancelable() {
					return false;
				}
			});
		}
	}

	public static String getMidletVer() {
		return main.getAppProperty("MIDlet-Version");
	}

	public static void notifyExit(){
		final ISIPContext sipContext = SIPManager.getSIPContext();
		if(sipContext != null){
			if(sipContext.resender != null){
				UDPDatagramConnection udpSocket = ((UDPDatagramConnection)sipContext.resender.getUDPSocket());
				if(udpSocket != null){
					try{
						udpSocket.close();
					}catch (Throwable e) {
						
					}
				}
			}
			try{
				sipContext.closeDeploySocket();
			}catch (Throwable e) {
			}
		}
		HCTimer.shutDown();
		try {
			Main.main.destroyApp(false);
		} catch (MIDletStateChangeException e) {
			e.printStackTrace();
		}
		Main.main.notifyDestroyed();
//		System.exit(0);
	}
	
	public static int gameWidth, gameHeight;
	public static boolean isTouchScreen;

}

class FirstGameCanvas extends GameCanvas{
	protected FirstGameCanvas(boolean suppressKeyEvents) {
		super(suppressKeyEvents);
		setFullScreenMode(true);
	}

	boolean isDone = false;
	
	public void paint(Graphics g) {
		if(isDone){
			return;
		}
		
		isDone = true;
		
		Main.gameWidth = getWidth();
		Main.gameHeight = getHeight();
		Main.isTouchScreen = hasPointerEvents();
		
		try {
			g.drawImage(Image.createImage("/hc/j2me/res/hc_64.png"), 
					getWidth()/2-32, getHeight()/2-32, Graphics.TOP|Graphics.LEFT);
		} catch (IOException e) {
		}
	}
}